/*
 * @Author: 一路向阳 tt_sunzhenfeng@163.com
 * @Date: 2024-05-15 12:47:46
 * @LastEditors: 一路向阳 tt_sunzhenfeng@163.com
 * @LastEditTime: 2024-05-15 15:16:06
 * @FilePath: \react_nest_demo\nest_service\src\utils\internalTools.ts
 * @Description: 加密配置
 */
import { BadRequestException, Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { createHash } from 'crypto';

// md5 加密的工具
@Injectable()
export class SecreTool {
  getSecret(data: string) {
    return createHash('md5').update(data).digest('hex');
  }
}

// token 解密
@Injectable()
export class JwtDecrypTool {
  constructor(private readonly jwtService: JwtService) {}

  getDecryp(token: string) {
    let decodedToken: any;

    try {
      decodedToken = this.jwtService.verify(token);
    } catch (error) {
      throw new BadRequestException('token 有误!');
    }

    if (!decodedToken) throw new BadRequestException('请先登录!');

    if (decodedToken.exp - decodedToken.iat <= 0)
      throw new BadRequestException('登录已过期，请重新登陆!');

    return decodedToken.id;
  }
}
